<?php

namespace App\Logic;

use App\Component\UserIdentity\BackendUser;
use App\Component\User;
use App\Core\BaseCore;
use App\Core\Exception\DefaultException;
use App\Enums\ValidateEnums;
use App\Lib\Util\Sms;
use App\Logic\Auth\UserService;
use App\Logic\Member\MemberService;
use App\Model\Member\MemberModel;
use App\Model\UserModel;
use App\Util\CommonHelper;
use App\Util\UserIdentityHelper;
use EasySwoole\Component\Di;
use EasySwoole\Component\Singleton;
use EasySwoole\EasySwoole\Config as ESConfig;
use EasySwoole\Redis\Redis;
use EasySwoole\RedisPool\RedisPool;

class BackendUserService extends BaseCore
{

    use Singleton;

    /**
     * 登陆操作
     * @param $username
     * @param $password
     * @return \App\Core\Output
     * @throws \App\Core\Exception\DefaultException
     * @throws \Throwable
     */
    public function login($username, $password)
    {
        /** @var User $user */
        $user = Di::getInstance()->get('user');

        if ($user->isLogin()) {
            return $this->success();
        }

        $userIdentity = BackendUser::findIdentityByUsername($username, $password);

        //登录操作重新获取权限
        /** @var Redis $cache */
        //        $cache = Di::getInstance()->get("REDIS");
        $cache = RedisPool::defer();
        $cache_key = "userInfoAuth:" . $userIdentity->id;
        if ($cache->exists($cache_key)) { //缓存存在
            //删除缓存
            $cache->del($cache_key);
        }

        $user->login($userIdentity);

        //放回前端需要的数据
        $return = [
            'username'      => $userIdentity->getUsername(),
            'name'          => $userIdentity->getName(),
            'avatar'        => $userIdentity->avatar,
            'type'          => $userIdentity->type,
            'menu_list'     => $userIdentity->getMenuTree(), //获取角色菜单
            'button'        => $userIdentity->getAuthList(), //按钮权限
        ];

        //更新最后登录时间
        if( $userIdentity->role == 'member'){
            //会员登录后台
            MemberModel::updateData(['last_admin_login_time' => CommonHelper::currentTime()], ['id' => $userIdentity->getId()]);
        }
        else {
            $this->updateUser($userIdentity->getId());
        }
        return $this->success($return);
    }

    /**
     * 更新用户信息
     * @param int $user_id
     * @return \App\Core\BaseModel|\EasySwoole\ORM\AbstractModel
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     */
    private function updateUser(int $user_id)
    {
        return UserModel::updateData(['last_login_time' => CommonHelper::currentTime()], ['id' => $user_id]);
    }

    /**
     * 修改密码
     * @param string password
     * @return \App\Core\Output
     * @throws \App\Core\Exception\DefaultException
     * @throws \Throwable
     */
    public function password(string $password)
    {
        if (empty($password)) {
            throw new DefaultException('请输入密码！');
        }

        //初始化密码
        list($password, $salt) = (new UserService)->getPassword($password);
        $user_id = UserIdentityHelper::getId();

        //更新信息
        $userModel = new UserModel();
        $res = $userModel->resetPassword($user_id, $password, $salt);
        if (!$res) {
            throw new DefaultException('更新密码失败！');
        }

        return $this->success();
    }
    /**
     * 修改用户密码
     *
     * @param string $username
     * @param string $password
     * @return \App\Core\Output
     * @throws \App\Core\Exception\DefaultException
     * @throws \Throwable
     */
    public function setPwd(string $username, string $password)
    {
        if (empty($username)) {
            throw new DefaultException('请选择用户');
        }
        if (empty($password)) {
            throw new DefaultException('请输入密码！');
        }
        //初始化密码
        list($password, $salt) = (new UserService)->getPassword($password);
        $currentUserId = UserIdentityHelper::getId();
        $userModel = new UserModel();
        $currentUser = $userModel->getOne(['id' => $currentUserId], true);
        $user = $userModel->getOne(['username' => $username], true);

        if (!$currentUser['id'] == UserModel::SUPER_ADMIN ) {
            $res = $userModel->resetPassword($user['id'], $password, $salt);
            if (!$res) {
                throw new DefaultException('更新密码失败！');
            }
        } else {
            throw new DefaultException('无权修改该用户密码');
        }
        return $this->success();
    }
    /**
     * 发送短信验证码
     * @param string $phone
     * @return \App\Core\Output
     * @throws DefaultException
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     */
    public function sendVerify($phone)
    {
        if (empty($phone)) {
            throw new DefaultException('请输入手机号码！');
        }

        if (!CommonHelper::isPhone($phone)) {
            throw new DefaultException('请输入正确手机号码！');
        }

        $orMap[] = "(username = '$phone' or phone like '$phone')";
        $exist = UserModel::makeQueryModel([], $orMap)->count();

        if ($exist > 0) {
            throw new DefaultException(ValidateEnums::get(ValidateEnums::EXISTS_MOBILE),ValidateEnums::EXISTS_MOBILE);
        }

        $SmsModel = new Sms();

        $code = $SmsModel->sendVerify($phone);

        $data = [];

        $debug = ESConfig::getInstance()->getConf('DEBUG');
        if ($debug) {
            $data['code'] = $code;
        }

        return $this->success($data);
    }
}
